/*
 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     bstefanescu
 */
package org.nuxeo.gwt.habyt.invocation.server;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.nuxeo.gwt.habyt.invocation.client.Invocation;
import org.nuxeo.gwt.habyt.invocation.client.InvocationException;
import org.nuxeo.gwt.habyt.invocation.client.InvocationResponse;

/**
 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
 * 
 */
public abstract class AnnotatedInvocationHandler implements InvocationHandler {

    private Map<String, Method> actions = new HashMap<String, Method>();

    public AnnotatedInvocationHandler() {
        actions = new HashMap<String, Method>();
        for (Method m : getClass().getMethods()) {
            Action action = m.getAnnotation(Action.class);
            if (action != null) {
                actions.put(action.value(), m);
            }
        }
    }

    @Override
    public void invoke(Invocation invocation, InvocationResponse response)
            throws Exception {
        Method m = actions.get(invocation.getAction());
        if (m == null) {
            throw new InvocationException("No such action: "
                    + invocation.getAction() + " for type "
                    + invocation.getTarget().getType());
        }
        try {
            m.invoke(this, invocation, response);
        } catch (InvocationTargetException e) {
            Throwable ee = e.getCause();
            if (ee == null) {
                throw e;
            }
            if (ee instanceof Exception) {
                throw (Exception) ee;
            } else {
                throw new InvocationException("Failed to invoke: "
                        + invocation.getAction() + " on object "
                        + invocation.getTarget(), ee);
            }
        }
    }

}
